<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./css/main.css">
</head>

<body>

    <button data-empty-cart>清空购物车</button>
    <table border="1">
        <thead>
            <tr>
                <th>名称</th>
                <th>价格</th>
                <th>原价</th>
                <th>数量</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody id="cartsList">
            <tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>
        </tbody>
    </table>

    <p>统计: <del id="totalPrice"></del> / <span id="totalSprice"></span></p>

    <div id="productsList"></div>
    <script>

        const productList = document.getElementById('productsList');
        const cartsList = document.getElementById('cartsList');

        // 商品列表
        // 1.定义商品数据(数组)
        const products = [
            { id: 1, name: 'name1', price: 100, store: 10, sprice: 15 },
            { id: 2, name: 'name2', price: 50, store: 5, sprice: 10 },
            { id: 3, name: 'name3', price: 70, store: 7, sprice: 50 },
            { id: 4, name: 'name4', price: 200, store: 4, sprice: 199 },
            { id: 5, name: 'name5', price: 200, store: 4, sprice: 99 },
        ];

        // 2. 将商品数据转化成HTML products=>html
        productsList.innerHTML = products.reduce((html, el) => {
            // 展示的数据放标签内,附属数据使用自定义属性
            html += `
            <div>
                <h2>${el.name}</h2>
                <button data-product-id="${el.id}">立即加入购物车</button>
            </div>
            `
            return html;
        }, '');

        // 3. 定义购物车的数据
        let carts = [
            { id: 1, product_id: 2, num: 3 },
            { id: 2, product_id: 4, num: 2 },
            { id: 3, product_id: 1, num: 1 },
            { id: 4, product_id: 3, num: 2 },
        ];

        // 4. 展示购物车 数据->html 创建购物车
        createCart(carts, products, cartsList)



        document.onclick = function (e) {
            const target = e.target;
            // 获取 productId 商品id
            const productId = target.dataset.productId;
            const addCartId = target.dataset.addCart;
            const decreaseCartId = target.dataset.decreaseCart;
            const deleteCartId = target.dataset.deleteCart;
            const emptyCart = target.dataset.emptyCart;
            // 5. 加入购物车
            if (productId !== undefined) {
                const i = carts.findIndex(el => el.product_id === +productId)
                if (i === -1) {
                    carts.push({ id: id(), product_id: +productId, num: 1 });
                } else {
                    carts[i].num++;
                }
                // 重新生成购物车
                createCart(carts, products, cartsList);
            }

            // 6. 修改商品数量+
            if (addCartId !== undefined) {
                // 根据 addCart id 获取修改的对象;
                const cartRow = carts.find(el => el.id === +addCartId);
                // 累加数量
                if (cartRow.num < cartRow.product.store) {
                    cartRow.num++;
                    // 根据新数据，重新生成一次购物车
                    createCart(carts, products, cartsList);
                }

            }

            // 7. 修改商品数量-
            if (decreaseCartId !== undefined) {
                // 根据 decreaseCartId 获取修改的对象;
                const cartRow = carts.find(el => el.id === +decreaseCartId);
                // 获取数据的索引
                const index = carts.findIndex(el => el.id === +decreaseCartId);
                if (cartRow.num > 1) {
                    // 递减数量
                    cartRow.num--;
                } else {
                    // 删除数据
                    carts.splice(index, 1);
                }
                // 根据新数据，重新生成一次购物车
                createCart(carts, products, cartsList);


            }
            // 8. 删除购物一行数据

            if (deleteCartId !== undefined) {
                // 根据 deleteCartId 获取数据的索引
                const index = carts.findIndex(el => el.id === +deleteCartId);
                // 删除数据
                carts.splice(index, 1);
                // 根据新数据，重新生成一次购物车
                createCart(carts, products, cartsList);
            }

            //  9. 清空购物车
            if (emptyCart !== undefined) {
                carts = [];
                // 根据新数据，重新生成一次购物车
                createCart(carts, products, cartsList);
            }

            // 每次点击统计价格
            totalCartPrice();

        }


        totalCartPrice();

        // 统计总价

        function totalCartPrice() {

            // 获取完整数据
            const allCarts = getFullCarts(carts, products);

            const total = allCarts.reduce((r, el) => {
                r.totalPrice += el.product.price * el.num;
                r.totalSprice += el.product.sprice * el.num;
                return r;
            }, { totalPrice: 0, totalSprice: 0 });


            totalPrice.innerHTML = total.totalPrice;
            totalSprice.innerHTML = total.totalSprice;
        }


        // 处理数据
        function getFullCarts(carts, products) {
            return carts.map(el => {
                // 根据product_id查找products数据
                el.product = products.find(pel => el.product_id === pel.id);
                return el;
            });
        }


        function id() {
            return Math.floor(Math.random() * 100000);
        }



        //  生成购物车

        function createCart(carts, products, el) {
            const fullCarts = getFullCarts(carts, products);
            el.innerHTML = fullCarts.reduce((html, el) => {
                html += `
            <tr>
                <td>${el.product.name}</td>
                <td>${el.product.price}</td>
                <td>${el.product.sprice}</td>
                <td><button data-decrease-cart="${el.id}">-</button> ${el.num}<button data-add-cart="${el.id}">+</button></td>
                <td>
                    <button data-delete-cart="${el.id}">X</button>
                </td>
            </tr>
            `
                return html;
            }, '')
        }





    </script>

</body>

</html>